package com.chushouya.controller;

import com.chushouya.common.dto.QueueMessage;
import com.chushouya.common.support.BaseMessageListener;
import com.chushouya.common.util.RabbitMQUtil;
import com.rabbitmq.client.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * RabbitMQ工具使用示例
 * 
 * @author chushouya team
 */
public class RabbitMQUsageExample {

    /**
     * 示例：发送消息的服务类
     */
    @Service
    @Slf4j
    public static class OrderService {
        
        @Autowired
        private RabbitMQUtil rabbitMQUtil;
        
        /**
         * 创建订单后发送消息
         */
        public void createOrder(Long orderId) {
            // 1. 发送普通消息
            rabbitMQUtil.sendMessage("order.created", orderId);
            
            // 2. 发送带类型的消息
            OrderCreatedEvent event = new OrderCreatedEvent(orderId, "PENDING");
            rabbitMQUtil.sendMessage("order.events", "ORDER_CREATED", event);
            
            // 3. 发送延时消息 - 30分钟后检查订单状态
            rabbitMQUtil.sendDelayMessage("order.check", orderId, 30, TimeUnit.MINUTES);
            
            // 4. 发送延时消息 - 1小时后自动取消未支付订单
            OrderCancelEvent cancelEvent = new OrderCancelEvent(orderId, "PAYMENT_TIMEOUT");
            rabbitMQUtil.sendDelayMessage("order.cancel", "ORDER_CANCEL", cancelEvent, 1, TimeUnit.HOURS);
            
            log.info("订单创建消息发送完成: {}", orderId);
        }
        
        /**
         * 支付成功后取消延时任务（通过发送取消消息）
         */
        public void paymentSuccess(Long orderId) {
            // 发送支付成功消息
            PaymentSuccessEvent event = new PaymentSuccessEvent(orderId);
            rabbitMQUtil.sendMessage("payment.success", "PAYMENT_SUCCESS", event);
            
            log.info("支付成功消息发送完成: {}", orderId);
        }
    }

    /**
     * 示例：消息监听器
     */
//    @Component
    @Slf4j
    public static class OrderMessageListener extends BaseMessageListener {
        
        /**
         * 监听订单创建消息
         */
        @RabbitListener(queues = "order.created")
        public void handleOrderCreated(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
            handleMessage(message, channel, deliveryTag);
        }
        
        /**
         * 监听订单事件消息
         */
        @RabbitListener(queues = "order.events")
        public void handleOrderEvents(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
            handleMessage(message, channel, deliveryTag);
        }
        
        /**
         * 监听订单检查消息（延时消息）
         */
        @RabbitListener(queues = "order.check")
        public void handleOrderCheck(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
            handleMessage(message, channel, deliveryTag);
        }
        
        /**
         * 监听订单取消消息（延时消息）
         */
        @RabbitListener(queues = "order.cancel")
        public void handleOrderCancel(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
            handleMessage(message, channel, deliveryTag);
        }
        
        /**
         * 监听支付成功消息
         */
        @RabbitListener(queues = "payment.success")
        public void handlePaymentSuccess(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
            handleMessage(message, channel, deliveryTag);
        }

        @Override
        protected boolean processMessage(QueueMessage<?> queueMessage) {
            try {
                String messageType = getMessageType(queueMessage);
                
                switch (messageType) {
                    case "ORDER_CREATED":
                        return handleOrderCreatedEvent(queueMessage);
                    case "ORDER_CANCEL":
                        return handleOrderCancelEvent(queueMessage);
                    case "PAYMENT_SUCCESS":
                        return handlePaymentSuccessEvent(queueMessage);
                    default:
                        return handleDefaultMessage(queueMessage);
                }
            } catch (Exception e) {
                log.error("处理消息异常: {}", e.getMessage(), e);
                return false;
            }
        }
        
        private boolean handleOrderCreatedEvent(QueueMessage<?> queueMessage) {
            OrderCreatedEvent event = getMessageData(queueMessage, OrderCreatedEvent.class);
            if (event == null) {
                log.error("订单创建事件数据为空");
                return false;
            }
            
            log.info("处理订单创建事件: orderId={}, status={}", event.getOrderId(), event.getStatus());
            
            // 这里实现具体的业务逻辑
            // 比如：发送短信、邮件通知等
            
            return true;
        }
        
        private boolean handleOrderCancelEvent(QueueMessage<?> queueMessage) {
            OrderCancelEvent event = getMessageData(queueMessage, OrderCancelEvent.class);
            if (event == null) {
                log.error("订单取消事件数据为空");
                return false;
            }
            
            log.info("处理订单取消事件: orderId={}, reason={}", event.getOrderId(), event.getReason());
            
            // 这里实现具体的业务逻辑
            // 比如：检查订单状态，如果未支付则取消订单
            
            return true;
        }
        
        private boolean handlePaymentSuccessEvent(QueueMessage<?> queueMessage) {
            PaymentSuccessEvent event = getMessageData(queueMessage, PaymentSuccessEvent.class);
            if (event == null) {
                log.error("支付成功事件数据为空");
                return false;
            }
            
            log.info("处理支付成功事件: orderId={}", event.getOrderId());
            
            // 这里实现具体的业务逻辑
            // 比如：更新订单状态、发货等
            
            return true;
        }
        
        private boolean handleDefaultMessage(QueueMessage<?> queueMessage) {
            Object data = queueMessage.getData();
            log.info("处理默认消息: messageId={}, data={}", queueMessage.getMessageId(), data);
            
            // 处理没有特定类型的消息
            if (data instanceof Long) {
                Long orderId = (Long) data;
                log.info("处理订单ID消息: {}", orderId);
                // 实现具体逻辑
            }
            
            return true;
        }

        @Override
        protected void handleDeadLetter(QueueMessage<?> queueMessage) {
            super.handleDeadLetter(queueMessage);
            
            // 自定义死信处理逻辑
            log.error("消息处理失败，记录到数据库: messageId={}, messageType={}", 
                    queueMessage.getMessageId(), queueMessage.getMessageType());
            
            // 这里可以实现：
            // 1. 记录到数据库
            // 2. 发送告警
            // 3. 人工处理队列
        }
    }

    // 事件类定义
    @Data
    public static class OrderCreatedEvent {
        private Long orderId;
        private String status;
        
        public OrderCreatedEvent() {}
        
        public OrderCreatedEvent(Long orderId, String status) {
            this.orderId = orderId;
            this.status = status;
        }
    }
    
    @Data
    public static class OrderCancelEvent {
        private Long orderId;
        private String reason;
        
        public OrderCancelEvent() {}
        
        public OrderCancelEvent(Long orderId, String reason) {
            this.orderId = orderId;
            this.reason = reason;
        }
    }
    
    @Data
    public static class PaymentSuccessEvent {
        private Long orderId;
        
        public PaymentSuccessEvent() {}
        
        public PaymentSuccessEvent(Long orderId) {
            this.orderId = orderId;
        }
    }
}
